const express = require('express')
const router = express.Router()
const models = require('../../models')
const {success, error} = require('../../utils/message')
const checkPermission = require('../../middlewares/check-permission');

/**
 * GET /admin/permissions
 * 列表
 */
router.get('/', checkPermission(), async function (req, res, next) {
   // 获取权限列表
    let permissions = await models.Permission.findAll({
        order: [['sort', 'ASC'], ['id', 'DESC']],
        where: {parentId: 0},
        include: [{
            model: models.Permission,
            as: 'children',
            separate: true,
            order: [['sort', 'ASC'], ['id', 'ASC']],
            include: [{
                model: models.Permission,
                as: 'children',
                separate: true,
                order: [['sort', 'ASC'], ['id', 'ASC']]
            }],
        }],
    })

    // 获取所有菜单
    let menus = await models.Permission.findAll({
        order: [['sort', 'ASC'], ['id', 'ASC']],
        where: {parentId: 0},
        include: [{
            model: models.Permission,
            as: 'children',
            separate: true,
            order: [['sort', 'ASC'], ['id', 'ASC']],
        }],
    })

    success(res, '查询成功', {permissions, menus})
})

/**
 * POST /admin/permissions
 * 新增
 */
router.post('/', checkPermission(), async function (req, res, next) {
    const title = req.body.title

    if (!title) {
        return error(res, '请设置权限标题')
    }

    const permission = await models.Permission.create(req.body)
    success(res, '新增成功', {permission})
})

/**
 * GET /admin/permissions/:id
 * 查询单条
 */
router.get('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const permission = await models.Permission.findByPk(id)
    if (!permission) {
        return error(res, '当前权限不存在')
    }

    success(res, '查询成功', {permission})
})

/**
 * PUT /admin/permissions/:id
 * 修改
 */
router.put('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const title = req.body.title

    if (!title) {
        return error(res, '请设置权限标题')
    }

    const permission = await models.Permission.findByPk(id)
    if (!permission) {
        return error(res, '当前权限不存在，无法修改')
    }

    permission.update(req.body)
    success(res, '修改成功', {permission})
})

/**
 * DELETE /admin/permissions/:id
 * 删除
 */
router.delete('/:id', checkPermission(), async function (req, res, next) {
    const id = req.params.id

    const permission = await models.Permission.findOne({
        where: {id: id},
        include: [{
            model: models.Permission,
            as: 'children',
        }],
    })

    if (!permission) {
        return error(res, '当前权限不存在，无法删除')
    }

    if (permission.level !== 3 && permission.children.length > 0) {
        return error(res, '当前权限有子权限，不能删除。请先将子权限删除后，再来操作！')
    }

    const rolePermissions = await models.RolePermission.count({where: {'permissionId': id}})
    if (rolePermissions.length > 0) {
        return error(res, '有用户组使用当前权限，不能删除。请先将调整用户组后，再来操作！')
    }

    permission.destroy()
    success(res, '删除成功')
})

/**
 * PATCH /admin/permissions/:id/change_sort
 * 修改排序
 */
// router.patch('/change_sort', checkPermission(), async function (req, res, next) {
//     const sorts = req.body.sorts
//
//     for (let i = 0; i < sorts.length; i++) {
//         const permission = await models.Permission.findByPk(sorts[i].id)
//         permission.update({sort: sorts[i].sort})
//     }
//
//     success(res, '修改排序成功 ')
// })

router.patch('/:id/change_sort', checkPermission(), async function (req, res, next) {
    const id = req.params.id
    const sort = req.body.sort

    if (!sort) {
        return error(res, '请填写排序')
    }

    if (!Number(sort)) {
        return error(res, '排序必须是数字')
    }

    const permission = await models.Permission.findByPk(id)
    if (!permission) {
        return error(res, '当前用户组不存在，无法修改排序')
    }

    permission.update({ sort: sort })
    success(res, '修改排序成功 ')
})
module.exports = router
